package org.github.manx98.jlibhac.fssystem;

import lombok.extern.slf4j.Slf4j;
import org.github.manx98.jlibhac.fs.IStorage;

import java.io.IOException;

@Slf4j
public class PartitionFileSystemHeader {
    public final String Magic;
    public final int NumFiles;
    public final int StringTableSize;
    public final long Reserved;
    public final PartitionFileSystemType Type;
    public final int HeaderSize;
    public final PartitionFileEntry[] Files;

    public PartitionFileSystemHeader(IStorage reader) throws IOException{
        Magic = reader.readAscii(4);
        NumFiles = reader.readInt();
        StringTableSize = reader.readInt();
        Reserved = reader.readInt();
        Type = PartitionFileSystemType.convert(Magic);
        if (Type == null) {
            throw new IllegalArgumentException("Invalid Partition FS type \"" + Magic + "\"");
        }
        int stringTableOffset = 16 + Type.entrySize * NumFiles;
        HeaderSize = stringTableOffset + StringTableSize;
        log.debug("PartitionFileSystemHeader={Magic:{}, NumFiles:{}, StringTableSize:{}}", Magic, NumFiles, StringTableSize);
        Files = new PartitionFileEntry[NumFiles];
        for (int i = 0; i < NumFiles; i++) {
            Files[i] = new PartitionFileEntry(reader, Type, i);
        }
        for (int i = 0; i < NumFiles; i++) {
            reader.setPosition(stringTableOffset + Files[i].stringTableOffset);
            Files[i].name = reader.readAsciiZ();
            log.debug("获取到文件名称:{}", Files[i]);
        }
    }
}
